package cn.jhc.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import cn.jhc.bean.Article;
import cn.jhc.bean.User;
import cn.jhc.db.DbFactory;

/**
 * Servlet implementation class PublishServlet
 */
@WebServlet("/user/publish.do")
public class PublishServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PublishServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("Content-type", "textml;charset=UTF-8");
		response.setCharacterEncoding("uft-8");
		response.setContentType("textml;charset=UTF-8");
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));

		String line = "";
		String message = "";
		while((line = bufferedReader.readLine()) != null) {
			message += line;
		}
		
		User currentUser = (User) request.getSession().getAttribute("currentUser");
		Article article = new Article();
		article.setContent(message);
		article.setPublish(new Date());
		article.setOwner(currentUser.getId());
		DbFactory.getArticleDao().create(article);
		response.setContentType("application/json; charset=utf8");
		PrintWriter out = response.getWriter();
		JSONObject object = new JSONObject();
		object.put("content", article.getContent());
		object.put("publish", article.getPublish());
		out.println(object.toString());

	}

}
